<?php
namespace app\a\controller;
use app\BaseController;
use think\facade\Db;
use qiniu\Qn;
use think\captcha\facade\Captcha;
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: x-token, x-uid, Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT, OPATION');
header('content-type:application/json;charset=utf8');
class Login extends BaseController{
    /*定义一个初始数组*/
    protected $info = array(
        'code'=>200,
        'msg'=>'提示',
        'total'=>0,//数据数量
        'data'=>[]
    );

    //写入操作日志
    protected function logData($action='',$admin_id=0){
        $pt['time'] = time();
        $pt['admin_id'] =  $admin_id;
        $pt['action'] =  trim($action);
        Db::table('an_admin_log')->insert($pt);
    }

    //上传七牛云文件
    public function upQiniuFile($prefix='family'){
        $qn = new Qn();
        $img = $qn->upFile(request(),$prefix);
        $this->info['code'] = 200;
        $this->info['data'] = $img;
        return json($this->info);
    }

    public function yzm()
    {
        return Captcha::create();    
    }

    //生成验证码
    public function verify(){

        //验证码标识
        $id=mt_rand(100000, 999999);
        $uniqid = uniqid("$id");
        //返回数据 验证码图片路径、验证码标识
        $data = [
            'src' =>captcha_src($uniqid),
            'uniqid' => $uniqid
        ];
        return json($data);
    }

    // 登录后台
    public function loginAdmin(){
        $pt = input("post.");
        $captcha = new Captcha();
        if($captcha::check($pt['code'])){
            $where = [
                'user'=>trim($pt['user']),
                'pass'=>md5('anan'.md5(trim($pt['pass'])))
            ];
            $adminData = Db::table('an_admin')
            ->where($where)
            ->field('id,name,user,login_time,role_id')
            ->select()
            ->toArray(); 
            if(count($adminData) > 0){
                $this->logData('登录系统',$adminData[0]['id']);
                Db::table('an_admin')->where('id', $adminData[0]['id'])->data(['login_time'=>time()])->update();
                $this->info['code'] = 200;
                $this->info['msg'] = '登录成功';
                $this->info['data'] = $adminData[0];
                return json($this->info);
            }else{
                $this->info['code'] = 201;
                $this->info['msg'] = '账号或密码有误';
                return json($this->info);
            }
        }else{
            $this->info['code'] = 201;
            $this->info['msg'] = '验证码有误'.$pt['code'];
            return json($this->info);
        }
    }

    public function isNot($code=200){
        $this->info['code'] = intval($code);
        if($code == 10001){
            $this->info['msg'] = '请求验证失败';
        }
        if($code == 10002){
            $this->info['msg'] = '请登录后再操作';
        }
        if($code == 10003){
            $this->info['msg'] = '账号不存在';
        }
        return json($this->info);
    }
}
